package com.ehotting.edsta.csharpServer.utils;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class HttpHelper {
	
	private final static Logger logger = LoggerFactory.getLogger(HttpHelper.class);
	
	/***
	 * 发起HttpGet请求
	 * 
	 * @param url
	 * @return
	 * @throws IOException
	 */
	public static String getHttp(String url, String responseDecode) throws IOException {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpGet httpget = new HttpGet(url);
		CloseableHttpResponse response = null;
		String content = null;
		try {
			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).setConnectionRequestTimeout(5000).build();
			httpget.setConfig(requestConfig);
			HashMap<String, String> headers = new HashMap<String, String>();  

			
			response = httpclient.execute(httpget);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				content = EntityUtils.toString(entity, responseDecode);
				EntityUtils.consume(entity);
			}
		} catch (ClientProtocolException e) {
			logger.error("request URL[" + url + "] error", e);
			throw e;
		} catch (IOException e) {
			logger.error("request URL[" + url + "] error", e);
			throw e;
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					logger.error("", e);
				}
			}
			if (httpclient != null) {
				try {
					httpclient.close();
				} catch (IOException e) {
					logger.error("", e);
				}
			}
		}
		return content;
	}

	/**
	 * 发送 post请求访问本地应用并根据传递参数不同返回不同结果
	 * 
	 * @throws IOException
	 */
	public static String postHttp(String url, Map<String, String> paramMap, Map<String, String> headerMap, String requestEncode, String responseDecode) throws IOException {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		CloseableHttpResponse response = null;
		List<NameValuePair> formParams = new ArrayList<NameValuePair>();
		if (paramMap != null) {
			for (String key : paramMap.keySet()) {
				formParams.add(new BasicNameValuePair(key, paramMap.get(key)));
			}
		}
		
		if (headerMap != null) {
			for (String key : headerMap.keySet()) {
				
				httpPost.addHeader(key, headerMap.get(key));
			}
		}
		String content = null;
		try {
			UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formParams, requestEncode);
			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).setConnectionRequestTimeout(5000).build();
			httpPost.setConfig(requestConfig);
			httpPost.setEntity(uefEntity);
			response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				content = EntityUtils.toString(entity, responseDecode);
				EntityUtils.consume(entity);
			}
		} catch (ClientProtocolException e) {
			logger.error("request URL[" + url + "] error", e);
			throw e;
		} catch (UnsupportedEncodingException e) {
			logger.error("request URL[" + url + "] error", e);
			throw e;
		} catch (IOException e) {
			logger.error("request URL[" + url + "] error", e);
			throw e;
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					logger.error("", e);
				}
			}
			if (httpClient != null) {
				try {
					httpClient.close();
				} catch (IOException e) {
					logger.error("", e);
				}
			}
		}
		return content;
	}

	
	/**
	 * 发送 post请求访问本地应用并根据传递参数不同返回不同结果
	 * 
	 * @throws IOException
	 */
	public static String postHttp(String url, String json, String requestEncode, String responseDecode) throws IOException {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		CloseableHttpResponse response = null;
		StringEntity se = new StringEntity(json, requestEncode);
		String content = null;
		try {
			httpPost.setEntity(se);
			response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				content = EntityUtils.toString(entity, responseDecode);
				EntityUtils.consume(entity);
			}
		} catch (ClientProtocolException e) {
			logger.error("request URL[" + url + "] error", e);
			throw e;
		} catch (UnsupportedEncodingException e) {
			logger.error("request URL[" + url + "] error", e);
			throw e;
		} catch (IOException e) {
			logger.error("request URL[" + url + "] error", e);
			throw e;
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					logger.error("", e);
				}
			}
			if (httpClient != null) {
				try {
					httpClient.close();
				} catch (IOException e) {
					logger.error("", e);
				}
			}
		}
		return content;
	}
	
	
	public static void downFile(String urlStr,String filePath,String charset){
		URL url = null;
		HttpURLConnection httpUrlConnection = null;
		InputStream fis = null;
		FileOutputStream fos = null;
		try {
		    url = new URL(urlStr);
		    httpUrlConnection = (HttpURLConnection) url.openConnection();
		    httpUrlConnection.setConnectTimeout(5 * 1000);
		    httpUrlConnection.setDoInput(true);
		    httpUrlConnection.setDoOutput(true);
		    httpUrlConnection.setUseCaches(false);
		    httpUrlConnection.setRequestMethod("GET");
		    httpUrlConnection.setRequestProperty("Charsert", "UTF-8");
		   
		    httpUrlConnection.connect();
		    fis = httpUrlConnection.getInputStream();
		    byte[] temp = new byte[1024];
		    int b;
		    fos = new FileOutputStream(new File(filePath));
		    while ((b = fis.read(temp)) != -1) {
		        fos.write(temp, 0, b);
		        fos.flush();
		    }
		} catch (MalformedURLException e) {
		    e.printStackTrace();
		} catch (IOException e) {
		    e.printStackTrace();
		} finally {
		    try {
		        fis.close();
		        fos.close();
		        httpUrlConnection.disconnect();
		    } catch (NullPointerException e) {
		        e.printStackTrace();
		    } catch (IOException e) {
		        e.printStackTrace();
		    }
		}
		
	}
	
}
